export default {
    name: 'Cart',
    props: {
      msg: String,
    },
    data() {
      return {
        showCart: false,
        cartData: [],
        allGood: [
          {
            name: '双肩包',
            price: 129,
            count: 5,
          },
          {
            name: '菠萝-广西很甜甜的菠萝新鲜好吃喔',
            price: 2,
            count: 5,
          },
          {
            name: '葡萄',
            price: 8,
            count: 5,
          },
          {
            name: '西瓜',
            price: 2,
            count: 12,
          },
        ],
      };
    },
    methods: {
      buy() {
        // console.error('object');
        // 计算总价
        let money = 0;
        for (let i = 0; i < this.cartData.length; i += 1) {
          money += this.cartData[i].price * this.cartData[i].count;
        }
        alert(`总价${money}`);
      },
      remove(item) {
        // console.error('rm:', item);
        for (let i = 0; i < this.cartData.length; i += 1) {
          if (this.cartData[i].name === item.name) {
            if (this.cartData[i].count > 1) {
              this.cartData[i].count -= 1;
              break;
            } else {
              this.cartData.splice(i, 1);
              break;
            }
          }
        }
      },
      add(item) {
        // 循环购物车，如果存在就加1，否则新增一个商品
        let flag = false;
        for (let i = 0; i < this.cartData.length; i += 1) {
          if (this.cartData[i].name === item.name) {
            this.cartData[i].count += 1;
            flag = true;
            break;
          }
        }
        if (!flag) {
          // 深拷贝一下，避免对象污染
          const one = JSON.parse(JSON.stringify(item));
          one.count = 1;
          this.cartData.push(one);
        }
      },
    },
  };